package com.boom.springapp.javafxdemo.common;

import java.util.*;

import lombok.Data;

@Data
public class Stat {
    private String name;
    private int location = 0;
    private Map<String, Integer> sex = new HashMap<>();
    private int[] level = new int[7];
    private int like = 0;
    private Set<String> users = new HashSet<>();
    private Map<String, String> userSexMap = new HashMap<>();

    // 构造函数
    public Stat() {
        initializeSexMap();
    }

    public Stat(String name) {
        this.name = name;
        initializeSexMap();
    }

    public Stat(String name, int location, int like) {
        this.name = name;
        this.location = location;
        this.like = like;
        initializeSexMap();
    }

    private void initializeSexMap() {
        sex.put("男", 0);
        sex.put("女", 0);
        sex.put("保密", 0);
    }

    // 用户数量属性
    public int getUserCount() {
        return users.size();
    }

    // 更新用户性别信息
    public void updateUserSex(String userId, String sex) {
        // 确保性别值有效
        if (!this.sex.containsKey(sex)) {
            sex = "保密";
        }

        // 如果用户已在性别映射中，则先减去之前统计的性别计数
        if (userSexMap.containsKey(userId)) {
            String oldSex = userSexMap.get(userId);
            if (this.sex.containsKey(oldSex)) {
                this.sex.put(oldSex, this.sex.get(oldSex) - 1);
            }
        }

        // 更新用户性别映射和计数
        userSexMap.put(userId, sex);
        if (this.sex.containsKey(sex)) {
            this.sex.put(sex, this.sex.get(sex) + 1);
        }
    }

    // 重新计算性别统计信息
    public void recalculateSexStats() {
        // 重置性别统计
        initializeSexMap();

        // 根据用户性别映射重新计算
        for (Map.Entry<String, String> entry : userSexMap.entrySet()) {
            String userSex = entry.getValue();
            if (sex.containsKey(userSex)) {
                sex.put(userSex, sex.get(userSex) + 1);
            }
        }
    }

    // 转换为Map，便于序列化
    public Map<String, Object> toMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", this.name);
        map.put("location", this.location);
        map.put("sex", this.sex);
        map.put("level", this.level);
        map.put("like", this.like);
        map.put("users", this.users.size()); // 只保存用户数量
        map.put("user_sex_map", this.userSexMap);
        return map;
    }
}

